//
//  GFFoodmarkViewController.m
//  GoodFood
//
//  Created by dllo on 15/11/3.
//  Copyright © 2015年 荣伟峰. All rights reserved.
//

#import "GFFoodmarkViewController.h"

@interface GFFoodmarkViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) NSMutableArray *tempArr;
@property (nonatomic, strong) UICollectionView *foodmarkCollectionView;
@property (nonatomic, strong) NSString *tomorrowDate;
@property (nonatomic, assign) NSInteger num;

@end

@implementation GFFoodmarkViewController
//获取明天的日期
-(NSString *)GetTomorrowDay:(NSDate *)aDate
{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
    [components setDay:([components day]+1)];
    
    NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
    NSDateFormatter *dateday = [[NSDateFormatter alloc] init];
    [dateday setDateFormat:@"yyyy-MM-dd"];
    return [dateday stringFromDate:beginningOfWeek];
}

-(void)handleData:(NSString *)date {
    self.app = [[UIApplication sharedApplication] delegate];
    NSString *url = [NSString stringWithFormat:@"http://api.meishixing.com/user/picturelist/footprint/uid=%@&session_id=%@&date=%@", self.user_id,self.app.session_id, date];
    [AFNetHandle GETWithURL:url body:nil httpHead:nil responseStyle:JSON success:^(id result) {
        
        if (self.num == 1) {
            self.tempArr = [NSMutableArray array];
        }
        
        NSArray *arr = [result objectForKey:@"result"];
        for (NSDictionary *dic in arr) {
            NSArray *arrr = [dic objectForKey:@"piclist"];
            NSDictionary *timeDic = @{@"date": dic[@"date"], @"count": dic[@"count"]};
            GFFoodmarkModel *model = [GFFoodmarkModel modWithDic:timeDic];
            [self.tempArr addObject:model];
            for (NSDictionary *dicc in arrr) {
                GFFoodmarkModel *model = [GFFoodmarkModel modWithDic:dicc];
                [self.tempArr addObject:model];
            }
            if ((arrr.count + 1) % 3 == 2) {
                NSDictionary *timeDic = @{@"date": @"1"};
                GFFoodmarkModel *model = [GFFoodmarkModel modWithDic:timeDic];
                [self.tempArr addObject:model];
            } else if ((arrr.count + 1) % 3 == 1) {
                NSDictionary *timeDic = @{@"date": @"1"};
                GFFoodmarkModel *model = [GFFoodmarkModel modWithDic:timeDic];
                [self.tempArr addObject:model];
                NSDictionary *timeDic1 = @{@"date": @"1"};
                GFFoodmarkModel *model1 = [GFFoodmarkModel modWithDic:timeDic1];
                [self.tempArr addObject:model1];
            }
        }
        [self.foodmarkCollectionView reloadData];
        if (arr.count != 0) {
            if (self.tempArr.count < 10) {
                self.foodmarkCollectionView.footer.hidden = YES;
            } else {
                self.foodmarkCollectionView.footer.hidden = NO;
            }
        } else {
            self.foodmarkCollectionView.footer.hidden = YES;
        }

    } fail:^(NSError *error) {
        
    }];
    
    
}

-(void)creatfoodmarkCollectionView {
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.itemSize = CGSizeMake((ScreenWidth - 41) / 3, (ScreenWidth - 41) / 3);
    NSLog(@"%f", ScreenWidth);
    NSLog(@"%f",(ScreenWidth - 41)/3);
    flow.minimumInteritemSpacing = 10;
    flow.minimumLineSpacing = 10;
    flow.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    flow.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.foodmarkCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64) collectionViewLayout:flow];
    self.foodmarkCollectionView.backgroundColor = [UIColor whiteColor];
    self.foodmarkCollectionView.delegate = self;
    self.foodmarkCollectionView.dataSource = self;
    [self.view addSubview:self.foodmarkCollectionView];
    
    [self.foodmarkCollectionView registerClass:[GFFoodmarkCollectionViewCell class] forCellWithReuseIdentifier:@"foodmark"];
    [self.foodmarkCollectionView registerClass:[GFFoodmarkDataCollectionViewCell class] forCellWithReuseIdentifier:@"data"];
    [self.foodmarkCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    self.foodmarkCollectionView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh:)];
    self.foodmarkCollectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footRefresh:)];
    
}

#pragma mark - 下拉刷新
- (void)headerRefresh:(MJRefreshHeader *)header {
    [self.foodmarkCollectionView.header beginRefreshing];
    self.num = 1;
    [self handleData:self.tomorrowDate];
    [self.foodmarkCollectionView.header endRefreshing];
}
#pragma mark - 上拉加载
- (void)footRefresh:(MJRefreshAutoNormalFooter *)footer {

    [self.foodmarkCollectionView.footer beginRefreshing];
    self.num = 0;
    for (GFFoodmarkModel *model in self.tempArr) {
        if (model.date != nil) {
            if (![model.date isEqualToString:@"1" ]) {
                self.tomorrowDate = model.date;
            }
        }
    }
    [self handleData:self.tomorrowDate];
    [self.foodmarkCollectionView.footer endRefreshing];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.foodmarkCollectionView.footer.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.num = 1;
    NSDate *sendDate=[NSDate date];
    self.tomorrowDate = [self GetTomorrowDay:sendDate];
    [self creatfoodmarkCollectionView];
    [self handleData:self.tomorrowDate];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.tempArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    GFFoodmarkModel *model = [self.tempArr objectAtIndex:indexPath.item];
    
    if (model.date != nil) {
        
        if (![model.date isEqualToString:@"1"]) {
            GFFoodmarkDataCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"data" forIndexPath:indexPath];
            cell.model = model;
            return cell;
            
        } else {
            
            UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
            cell.backgroundColor = [UIColor clearColor];
            return cell;
            
        }
        
    } else {
        
        GFFoodmarkCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"foodmark" forIndexPath:indexPath];
        cell.model = model;
        return cell;
        
    }
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    GFFoodmarkModel *model = [self.tempArr objectAtIndex:indexPath.item];
    if (model.date == nil) {
        GFNearHomeDetialViewController *detialVC = [[GFNearHomeDetialViewController alloc] init];
        detialVC.i = 300;
        detialVC.tweet_id = model.tweet_id;
        [self.navigationController pushViewController:detialVC animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
